﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace be.metanous.mvvm.converters
{
    public class NullConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var mode = parameter is NullConverterParameter
                           ? (NullConverterParameter) parameter
                           : NullConverterParameter.TrueToNull;
            switch (mode)
            {
                case NullConverterParameter.TrueToNull:
                    return (value is bool && (bool) value) ? null : value;
                case NullConverterParameter.FalseToNull:
                    return (value is bool && !(bool)value) ? null : value;
                case NullConverterParameter.UnsetToNull:
                    return (DependencyProperty.UnsetValue.Equals(value)) ? null : value;
                case NullConverterParameter.NotUnsetToNull:
                    return (!DependencyProperty.UnsetValue.Equals(value)) ? null : value;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var mode = parameter is NullConverterParameter
                         ? (NullConverterParameter)parameter
                         : NullConverterParameter.TrueToNull;
            switch (mode)
            {
                case NullConverterParameter.TrueToNull:
                    return (value == null ) ? true : false;
                case NullConverterParameter.FalseToNull:
                    return (value != null) ? true : false;
                case NullConverterParameter.UnsetToNull:
                    throw new NotImplementedException();
                case NullConverterParameter.NotUnsetToNull:
                    throw new NotImplementedException();
            }
            return false;
        }
    }
}
